const common = require('consts.js')

var requestHandler = {
  actoin: '',
  data: {},
  showSuccess: false, // 请求成功 弹 msg
  showError: false,  // 请求失败 弹 msg
  complete: function(code, msg, data) {
  }
}
//GET请求
function GET(requestHandler) {
  request('GET', requestHandler)
}
//POST请求
function POST(requestHandler) {
  request('POST', requestHandler)
}

//DELETE请求
function DELETE(requestHandler) {
  request('DELETE', requestHandler)
}

//PUT请求
function PUT(requestHandler) {
  request('PUT', requestHandler)
}

function request(method, requestHandler) {
  wx.request({
    url: common.api_host + requestHandler.action,
    data: requestHandler.data,
    method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      "Accept": "application/json",
      "Authorization": "Token " + wx.getStorageSync('token'),
      "Content-Type": "application/json; charset=UTF-8;"
    }, // 设置请求的 header
    success: function (res) {
      //注意：可以对参数解密等处理
      if (requestHandler.showSuccess || requestHandler.showError) {
        var title
        if (title = res.data.msg) {
          wx.showToast({
            title: title,
          })
        }
      }
      if (requestHandler.complete) {
        requestHandler.complete(res.data.code, res.data.msg, res.data.data)
      }
    },
    fail: function () {
      if (requestHandler.showSuccess || requestHandler.showError) {
        wx.showToast({
          title: '网络异常',
        })
      }
      if (requestHandler.complete) {
        requestHandler.complete(-1, '网络异常', null)
      }
    },
    complete: function () {
    }
  })
}

function updateAlbumImages(handler) {
  var images = handler.images
  var result = []

  function uploadImage(index) {
    if (index >= images.length) {
      handler.complate(result)
      return
    }
    var imagePath = images[index]
    
    var url = common.api_host + '/wxapi/albums/' + handler.albumId + '/res/'

    wx.uploadFile({
      url: url,
      filePath: imagePath,
      name: 'image',
      header: {
        "Authorization": "Token " + wx.getStorageSync('token'),
      },
      success: function (res) {
        var res = JSON.parse(res.data)
        if(res.code == 0) {
          result.push(res.data)
        }
        uploadImage(index+1)
        handler.progress(index)
      }
    })
  }
  uploadImage(0)
}

module.exports = {
  GET: GET,
  POST: POST,
  DELETE: DELETE,
  PUT: PUT,
  updateAlbumImages: updateAlbumImages
}